package com.sanji.sjmallmanager.http;

import android.content.Context;

import com.sanji.sjmallapp.R;
import com.sanji.sjmallutils.Tools;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;

/**
 * 单例模式 -- 提供外部调用进行网络请求
 * Created by zsf on 16-12-9.
 */

public class NoHttpCallBack {
    private final RequestQueue mQueue;
    private static NoHttpCallBack callService;

    private NoHttpCallBack() {
        mQueue = NoHttp.newRequestQueue();
    }
    //把生成队列写成懒汉单例模式,因为每新建队列就会new出相应个数的线程来，同时只有线程数固定了，队列的作用才会发挥到最大。
    public synchronized static NoHttpCallBack getInstance() {
        if (callService == null) {
            callService = new NoHttpCallBack();
        }
        return callService;
    }

    public RequestQueue getRequestQueue() {
        return mQueue;
    }

    /**
     * 添加一个请求到队列中
     *
     * @param context
     * @param what
     * @param request
     * @param httpListener
     * @param canCancle    -- 可取消
     * @param isLoading    -- 是否显示加载等待
     * @param <T>
     */
    public <T> void add(Context context, int what, Request<T> request, NoHttpListener<T> httpListener, Boolean canCancle, Boolean isLoading) {
        if (context != null) {
            if (!Tools.isNetwork(context)) {
                Tools.toastTools(context, context.getString(R.string.request_net_out));
                return;
            } else {
                mQueue.add(what, request, new NoHttpManager<T>(context, request, httpListener, canCancle, isLoading));
            }
        }
    }
}
